<template>
  <div class="login-background">
    <el-container class="login-container">
      <div class="login-card">
        <div class="login-header">
          <h2>系统登录</h2>
          <p>欢迎使用管理系统</p>
        </div>

        <el-tabs v-model="activeName" @tab-click="handleTabClick" class="login-tabs">
          <el-tab-pane label="密码登录" name="passwordLogin">
            <el-form ref="pwdLoginFormRef" :model="state.passwordForm" :rules="state.pwdLoginRules" class="login-form">
              <el-form-item prop="username">
                <el-input
                    v-model="state.passwordForm.username"
                    placeholder="请输入用户名"
                    prefix-icon="User"
                    size="large"
                    clearable>
                </el-input>
              </el-form-item>
              <el-form-item prop="password">
                <el-input
                    v-model="state.passwordForm.password"
                    @keyup.enter="pwdLoginSubmit"
                    type="password"
                    placeholder="请输入密码"
                    prefix-icon="Lock"
                    size="large"
                    show-password>
                </el-input>
              </el-form-item>
              <div class="login-button">
                <el-button
                    type="primary"
                    @click="pwdLoginSubmit"
                    :loading="state.loading"
                    size="large"
                    round
                    class="login-submit-btn">
                  立即登录
                </el-button>
              </div>
            </el-form>
          </el-tab-pane>

          <el-tab-pane label="微信登录" name="weixinLogin">
            <div class="login-center">
              <div class="qrcode-container">
                <img
                    v-if="state.qrCodeUrl"
                    :src="state.qrCodeUrl"
                    width="200"
                    height="200"
                    alt="WeChat QR Code"
                    class="qrcode-img"/>
                <img
                    v-else
                    src="/src/assets/img/refersh-qrcode.png"
                    @click="loadWxQrCode"
                    class="refresh-qrcode"
                    alt="微信扫描二维码"/>
              </div>
              <div class="qrcode-tip">请使用微信扫码登录</div>
              <div class="qrcode-sub-tip">扫描二维码关注公众号并登录</div>
            </div>
          </el-tab-pane>

          <el-tab-pane label="验证码登录" name="smsLogin">
            <el-form ref="smsLoginFormRef" :model="state.smsCaptchaForm" :rules="state.smsCaptchaRules" class="login-form">
              <el-form-item prop="phoneNumber">
                <el-input
                    v-model="state.smsCaptchaForm.phoneNumber"
                    placeholder="请输入手机号"
                    prefix-icon="Phone"
                    size="large">
                </el-input>
              </el-form-item>

              <el-form-item v-if="state.needCaptcha" prop="captchaCode">
                <div class="captcha-container">
                  <el-input
                      v-model="state.smsCaptchaForm.captchaCode"
                      placeholder="图片验证码"
                      size="large">
                  </el-input>
                  <img
                      v-if="state.captchaUrl"
                      :src="state.captchaUrl"
                      alt="图片验证码"
                      class="captcha-img"
                      @click="loadPictureCaptcha()"/>
                </div>
              </el-form-item>

              <el-form-item>
                <div class="sms-captcha-container">
                  <el-input
                      v-model="state.smsCaptchaForm.smsCaptcha"
                      placeholder="短信验证码"
                      size="large">
                  </el-input>
                  <el-button
                      @click="sendVerificationCode"
                      :disabled="state.sms.isSending"
                      type="primary"
                      class="sms-send-btn">
                    {{ state.sms.isSending ? state.sms.countdown + '秒后重试' : '发送验证码' }}
                  </el-button>
                </div>
              </el-form-item>

              <div class="login-button">
                <el-button
                    type="primary"
                    @click="smsLoginSubmit"
                    :loading="state.loading"
                    size="large"
                    round
                    class="login-submit-btn">
                  立即登录
                </el-button>
              </div>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-container>
  </div>
</template>

<script setup>
import {onMounted, reactive, ref} from 'vue';
import {useRouter} from "vue-router";
import {ElMessage} from 'element-plus';
import {getQrCode, pullLogin} from "@/api";
import {getCaptcha, getNeedCaptcha, sendSmsCode, systemLogin} from "@/api/login";

const router = useRouter();
const activeName = ref('passwordLogin');

const state = reactive({
  needCaptcha: null,
  captchaId: '',
  captchaUrl: "",
  loading: false,
  year: new Date().getFullYear(),
  sid: "",
  qrCodeUrl: '',
  passwordForm: {
    username: '',
    password: ''
  },
  pwdLoginRules: {
    username: [
      {required: true, message: 'Please input your username', trigger: 'blur'},
    ],
    password: [
      {required: true, message: 'Please input your password', trigger: 'blur'},
    ]
  },
  sms: {
    isSending: false,
    countdown: 60,
  },
  smsCaptchaForm: {
    phoneNumber: '',
    captchaId: '',
    captchaCode: '',
    smsCaptcha: ''
  },
  smsCaptchaRules: {
    phoneNumber: [
      {required: true, message: 'Please input your phone number', trigger: 'blur'},
      {
        validator: (rule, value, callback) => {
          if (!/^\d{11}$/.test(value)) {
            callback(new Error('Phone number must be 11 digits'));
          } else {
            callback();
          }
        },
        trigger: 'blur'
      }
    ],
    captchaCode: [
      {required: true, message: 'Please input the captcha', trigger: 'blur'}
    ]
  }
});

//密码登录验证表单
const pwdLoginFormRef = ref(null);
//短信登录验证表单
const smsLoginFormRef = ref(null);

let pollingInterval = null;
// 切换tab
const handleTabClick = (tab) => {
  activeName.value = tab.props.name;
  if (activeName.value === 'weixinLogin') {
    loadWxQrCode();
  } else {
    clearInterval(pollingInterval)
  }
};

//加载微信二维码
const loadWxQrCode = () => {
  let query = {sid: state.sid}
  getQrCode(query).then(res => {
    state.sid = res.data.sid;
    state.qrCodeUrl = res.data.img
    pollingInterval = setInterval(() => {
      let query = {sid: state.sid}
      pullLogin(query).then(res => {
        if (res.code === 300) {
          console.log("请扫描二维码");
        } else {
          clearInterval(pollingInterval)
          if (res.code === 200) {
            console.log("登录成功");
          } else if (res.code === 400) {
            console.log("二维码已失效")
            state.qrCodeUrl = "";
          } else {
            console.log("登录失败");
          }
        }
      })
    }, 2000);
  })
}

//加载图片验证码
const loadPictureCaptcha = () => {
  getCaptcha().then(res => {
    state.captchaUrl = res.data.image
    state.smsCaptchaForm.captchaId = res.data.uuid
  })
}

//延迟1秒模拟登录请求
const delayedAction = () => {
  setTimeout(() => {
    ElMessage.success('Login success!');
    localStorage.setItem('token', 'testToken123');
    localStorage.setItem('username', 'admin');
    router.push({path: '/'});
  }, 2000);
}

//密码登录提交
const pwdLoginSubmit = () => {
  pwdLoginFormRef.value.validate((valid) => {
    if (valid) {
      state.loading = true;
      let loginData = {
        loginType: 'PASSWORD',
        principal: state.passwordForm.username,
        credential: state.passwordForm.password,
      }
      systemLogin(loginData).then(res => {
        if (res.code === 200) {
          localStorage.setItem('token', res.data.token);
          localStorage.setItem('username', res.data.realName);
          ElMessage.success('Login success!');
          router.push({path: '/'});
        } else {
          ElMessage.error(res.msg);
        }
        state.loading = false;
      })
    } else {
      ElMessage.error('Invalid username or password!');
    }
  });
};

//短信登录提交
const smsLoginSubmit = () => {
  smsLoginFormRef.value.validate((valid) => {
    if (valid) {
      state.loading = true;
      delayedAction();
    } else {
      ElMessage.error('Invalid username or password!');
    }
  });
};

//发送短信验证码
const sendVerificationCode = async () => {
  if (state.sms.isSending) return;
  smsLoginFormRef.value.validate((valid) => {
    if (valid) {
      try {
        // 这里可以调用发送验证码的API
        let postData = {
          captchaId: state.smsCaptchaForm.captchaId,
          captchaCode: state.smsCaptchaForm.captchaCode,
          phoneNumber: state.smsCaptchaForm.phoneNumber
        }
        sendSmsCode(postData).then(res => {
          if (res.code === 200) {
            state.sms.isSending = true;
            setInterval(() => {
              state.sms.countdown--;
              if (state.sms.countdown <= 0) {
                state.sms.isSending = false;
                state.sms.countdown = 60;
              }
            }, 1000)
          } else {
            ElMessage.error(res.msg);
          }
        })
      } catch (error) {
        ElMessage.error('发送验证码失败');
      } finally {
        state.sms.isSending = false;
      }
    }
  })
};

onMounted(() => {
    getNeedCaptcha().then(res => {
      state.needCaptcha = res.data;
      loadPictureCaptcha();
    })
})
</script>

<style scoped>
.login-background {
  /*background: linear-gradient(135deg, #D0CBD5FF 0%, #d0cbd5 100%);*/
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
}

.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 500px;
  background: transparent;
}

.login-card {
  width: 450px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 12px;
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  padding: 30px;
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-header h2 {
  font-size: 24px;
  color: #333;
  margin-bottom: 10px;
}

.login-header p {
  color: #666;
  font-size: 14px;
}

.login-tabs {
  border: none;
}

.login-tabs :deep(.el-tabs__header) {
  margin-bottom: 30px;
}

.login-tabs :deep(.el-tabs__nav-wrap)::after {
  background-color: transparent;
}

.login-tabs :deep(.el-tabs__item) {
  font-size: 16px;
  color: #666;
  padding: 0 20px;
}

.login-tabs :deep(.el-tabs__item.is-active) {
  color: #409eff;
  font-weight: 500;
}

.login-tabs :deep(.el-tabs__active-bar) {
  background-color: #409eff;
  height: 3px;
}

.login-form {
  padding: 0;
  background-color: transparent;
  box-shadow: none;
}

.login-form :deep(.el-form-item) {
  margin-bottom: 25px;
}

.login-form :deep(.el-input__wrapper) {
  border-radius: 8px;
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}

.login-form :deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #409eff inset;
}

.captcha-container {
  display: flex;
  gap: 10px;
  align-items: center;
}

.captcha-container :deep(.el-input) {
  flex: 1;
}

.captcha-img {
  height: 40px;
  border-radius: 4px;
  cursor: pointer;
  border: 1px solid #dcdfe6;
}

.sms-captcha-container {
  display: flex;
  gap: 10px;
  align-items: center;
}

.sms-captcha-container :deep(.el-input) {
  flex: 1;
}

.sms-send-btn {
  height: 40px;
  border-radius: 8px;
}

.login-button {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.login-submit-btn {
  width: 100%;
  height: 45px;
  font-size: 16px;
  border-radius: 8px;
}

.login-center {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px 0;
}

.qrcode-container {
  padding: 20px;
  background: #f5f5f5;
  border-radius: 10px;
  margin-bottom: 20px;
}

.qrcode-img {
  display: block;
}

.refresh-qrcode {
  width: 200px;
  height: 200px;
  cursor: pointer;
}

.qrcode-tip {
  font-size: 16px;
  color: #333;
  margin-bottom: 5px;
}

.qrcode-sub-tip {
  font-size: 14px;
  color: #999;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .login-card {
    width: 90%;
    margin: 20px;
    padding: 20px;
  }
}
</style>